<template>
  <div class="security-settings">
    <el-card class="box-card">
      <h2>安全设置</h2>

      <!-- 手机 -->
      <el-row class="setting-item">
        <el-col :span="6">
          <strong>手机</strong>
        </el-col>
        <el-col :span="12">
          <span>{{ phone || '未绑定' }}</span>
        </el-col>
        <el-col :span="6" class="action-buttons">
          <el-button type="text" @click="showChangePhoneDialog = true" v-if="phone">更换</el-button>
          <el-button type="text" @click="showPhoneDialog = true" v-else>绑定</el-button>
        </el-col>
      </el-row>

      <el-divider />

      <!-- 邮箱 -->
      <el-row class="setting-item">
        <el-col :span="6">
          <strong>邮箱</strong>
        </el-col>
        <el-col :span="12">
          <span>{{ email || '未绑定' }}</span>
        </el-col>
        <el-col :span="6" class="action-buttons">
          <el-button type="text" @click="showChangeEmailDialog = true" v-if="email">更换</el-button>
          <el-button type="text" @click="showEmailDialog = true" v-else>绑定</el-button>
        </el-col>
      </el-row>

      <el-divider />

      <!-- 微信 -->
      <el-row class="setting-item">
        <el-col :span="6">
          <strong>微信</strong>
        </el-col>
        <el-col :span="12">
        </el-col>
        <el-col :span="6" class="action-buttons">
          <el-button type="text" @click="showWechatDialog = true">绑定</el-button>
        </el-col>
      </el-row>

      <el-divider />

      <!-- QQ -->
      <el-row class="setting-item">
        <el-col :span="6">
          <strong>QQ</strong>
        </el-col>
        <el-col :span="12">
        </el-col>
        <el-col :span="6" class="action-buttons">
          <el-button type="text" @click="showQQDialog = true">绑定</el-button>
        </el-col>
      </el-row>

    </el-card>

    <!-- 手机绑定弹窗 -->
    <el-dialog title="绑定手机号" v-model="showPhoneDialog" width="400px">
      <el-form :model="phoneForm" :rules="phoneRules" ref="phoneFormRef" label-width="80px">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="phoneForm.phone" placeholder="请输入新的手机号"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="phoneForm.code" placeholder="请输入验证码"></el-input>
          <el-button @click="sendCode" :disabled="countdown > 0">{{ countdown > 0 ? `${countdown}s后重发` : '获取验证码' }}</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showPhoneDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmPhone">确定</el-button>
      </div>
    </el-dialog>

    <!-- 更换手机号弹窗 -->
    <el-dialog title="更换手机号" v-model="showChangePhoneDialog" width="400px">
      <el-form :model="changePhoneForm" :rules="phoneRules" ref="changePhoneFormRef" label-width="80px">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="changePhoneForm.phone" placeholder="请输入新的手机号"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="changePhoneForm.code" placeholder="请输入验证码"></el-input>
          <el-button @click="sendChangePhoneCode" :disabled="phoneCountdown > 0">{{ phoneCountdown > 0 ? `${phoneCountdown}s后重发` : '获取验证码' }}</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showChangePhoneDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmChangePhone">确定</el-button>
      </div>
    </el-dialog>

    <!-- 邮箱绑定弹窗 -->
    <el-dialog title="绑定邮箱" v-model="showEmailDialog" width="400px">
      <el-form :model="emailForm" :rules="emailRules" ref="emailFormRef" label-width="80px">
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="emailForm.email" placeholder="请输入邮箱地址"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="emailForm.code" placeholder="请输入验证码"></el-input>
          <el-button @click="sendEmailCode" :disabled="emailCountdown > 0">{{ emailCountdown > 0 ? `${emailCountdown}s后重发` : '获取验证码' }}</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showEmailDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmEmail">确定</el-button>
      </div>
    </el-dialog>

    <!-- 更换邮箱弹窗 -->
    <el-dialog title="更换邮箱" v-model="showChangeEmailDialog" width="400px">
      <el-form :model="changeEmailForm" :rules="emailRules" ref="changeEmailFormRef" label-width="80px">
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="changeEmailForm.email" placeholder="请输入新的邮箱地址"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="changeEmailForm.code" placeholder="请输入验证码"></el-input>
          <el-button @click="sendChangeEmailCode" :disabled="emailCountdown > 0">{{ emailCountdown > 0 ? `${emailCountdown}s后重发` : '获取验证码' }}</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showChangeEmailDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmChangeEmail">确定</el-button>
      </div>
    </el-dialog>


  </div>

  <!-- 微信绑定弹窗 -->
  <el-dialog title="绑定微信" v-model="showWechatDialog" width="400px">
    <p style="text-align: center; font-size: 16px; color: #666;">绑定微信功能待实现!</p>
    <template #footer>
      <el-button @click="showWechatDialog = false">关闭</el-button>
    </template>
  </el-dialog>

  <!-- QQ绑定弹窗 -->
  <el-dialog title="绑定QQ" v-model="showQQDialog" width="400px">
    <p style="text-align: center; font-size: 16px; color: #666;">绑定QQ功能待实现!</p>
    <template #footer>
      <el-button @click="showQQDialog = false">关闭</el-button>
    </template>
  </el-dialog>

</template>

<script>
export default {
  data() {
    return {
      phone: "", // 从后端读取的手机号
      email: "", // 从后端读取的邮箱
      showPhoneDialog: false, // 手机绑定弹窗显示控制
      showChangePhoneDialog: false, // 手机更换弹窗显示控制
      showEmailDialog: false, // 邮箱绑定弹窗显示控制
      showChangeEmailDialog: false, // 邮箱更换弹窗显示控制
      showPasswordDialog: false, // 修改密码弹窗显示控制
      showWechatDialog: false, // 控制微信绑定弹窗的显示
      showQQDialog:false, // 控制 QQ绑定弹窗的显示
      phoneForm: {
        phone: "",
        code: "",
      },
      emailForm: {
        email: "",
        code: "",
      },
      changeEmailForm: {
        email: "",
        code: "",
      },
      changePhoneForm: {
        phone: "", // 新手机号
        code: "",  // 验证码
      },
      passwordForm: {
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
      },
      countdown: 0, // 手机验证码倒计时
      emailCountdown: 0, // 邮箱验证码倒计时
      phoneCountdown: 0, // 手机验证码倒计时
      phoneRules: {
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { pattern: /^[1][3-9][0-9]{9}$/, message: "手机号格式不正确", trigger: "blur" },
        ],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
      emailRules: {
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { type: "email", message: "邮箱格式不正确", trigger: "blur" },
        ],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
    };
  },
  created() {
    this.fetchUserInfo();
  },

  methods: {
    // 发送手机验证码
    async sendCode() {
      if (this.countdown > 0) return; //如果倒计时大于0，返回，防止频繁发送验证码
      // 假设调用接口
      try {
        const identifier = this.phoneForm.phone; //获取用户的手机号
        const response = await fetch(`/api/api/sms/send?phone=${encodeURIComponent(identifier)}`, {
          method: "GET", // 使用 GET 请求发送
        });
        // 处理响应
        const result = await response.json(); //解析响应体为json格式
        if (result.code === "200") { //判断接口返回的状态是否为200
          this.$message.success(`${result.data}`); //弹出成功信息，显示返回的数据
          this.startCountdown(); // 启动手机验证码倒计时
        } else {
          this.$message.error(`发送验证码失败: ${result.message}`); // 如果返回的code不是200，弹出错误信息
        }
      } catch (error) { //捕获请求过程中的错误
        console.error("发送手机号验证码失败:", error);
        this.$message.error("发送验证码失败，请稍后重试！"); //弹出请求失败的错误提示
      }
    },
    // 发送更换手机号验证码
    async sendChangePhoneCode() {
      if (this.phoneCountdown > 0) return; // 防止重复发送
      try {
        const phone = this.changePhoneForm.phone; // 新手机号
        const response = await fetch(`/api/api/sms/send?phone=${encodeURIComponent(phone)}`, {
          method: "GET",
        });

        const result = await response.json();
        if (result.code === "200") {
          this.$message.success("验证码已发送！");
          this.startCountdown(); // 启动验证码倒计时
        } else {
          this.$message.error(`发送验证码失败: ${result.message}`);
        }
      } catch (error) {
        console.error("发送验证码失败:", error);
        this.$message.error("发送验证码失败，请稍后重试！");
      }
    },

    // 确认更换手机号
    async confirmChangePhone() {
      try {
        const params = {
          username: "xju1001", // 替换为实际用户名
          tel: this.changePhoneForm.phone,
          code: this.changePhoneForm.code,
        };

        const response = await fetch("/api/api/sms/bind", {
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
          body: `username=${encodeURIComponent(params.username)}&tel=${encodeURIComponent(params.tel)}&code=${encodeURIComponent(params.code)}`,
        });

        const result = await response.json();
        if (result.code === "200") {
          this.$message.success("手机号更换成功！");
          this.fetchUserInfo(); // 在成功回调中重新加载用户信息
          this.showChangePhoneDialog = false; // 关闭弹窗
        } else {
          this.$message.error(`更换失败: ${result.message}`);
        }
      } catch (error) {
        console.error("更换手机号失败:", error);
        this.$message.error("更换手机号失败，请稍后重试！");
      }
    },

    // 手机验证码倒计时
    startCountdown() {
      this.countdown = 60;
      const timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          clearInterval(timer);
        }
      }, 1000);
    },

    // 确认绑定手机号
    async confirmPhone() {
      // 假设调用接口
      try {
        let params = {
          username: 'xju1001',
          tel: this.phoneForm.phone,
          code: this.phoneForm.code,
        } // 构建请求参数对象
        const response = await fetch(`/api/api/sms/bind`, {
          method: "POST", //使用POST发送请求
          body:`username=lisi&tel=${this.phoneForm.phone}&code=${this.phoneForm.code}`, //
          headers:{
            'Content-Type':'application/x-www-form-urlencoded', //
          }
        });

        const result = await response.json(); // 解析响应体为json格式
        if (result.code === "200") { // 判断接口返回的状态是否为200
          this.$message.success(`添加成功`); // 弹出成功信息，显示返回的数据
          this.showPhoneDialog = false; // 关闭绑定手机号弹窗
        } else {
          this.$message.error(`添加失败: ${result.message}`); // 如果返回的code不是200，表示失败，弹出错误信息
        }
      } catch (error) {  // 捕获请求过程中的错误
        console.error("添加失败:", error);
        this.$message.error("添加失败，请稍后重试！"); // 弹出请求失败的错误提示
      }
    },

    // 发送绑定邮箱验证码
    async sendEmailCode() {
      if (this.emailCountdown > 0) return; // 防止倒计时期间多次发送验证码

      try {
        const email = this.emailForm.email; // 获取邮箱地址
        const response = await fetch(`/api/api/email/send?email=${encodeURIComponent(email)}`, {
          method: "GET", // 使用 GET 请求
        });

        const result = await response.json();
        if (result.code === "200") {
          this.$message.success(`${result.data}`); // 显示验证码发送成功的消息
          this.startEmailCountdown(); // 启动邮箱验证码倒计时
        } else {
          this.$message.error(`发送验证码失败: ${result.message}`); // 显示失败消息
        }
      } catch (error) {
        console.error("发送邮箱验证码失败:", error);
        this.$message.error("发送验证码失败，请稍后重试！"); // 显示请求失败的错误提示
      }
    },
    // 发送更换邮箱的验证码
    async sendChangeEmailCode() {
      if (this.emailCountdown > 0) return; // 防止重复发送
      try {
        const email = this.changeEmailForm.email; // 新邮箱地址
        const response = await fetch(`/api/api/email/send?email=${encodeURIComponent(email)}`, {
          method: "GET",
        });

        const result = await response.json();
        if (result.code === "200") {
          this.$message.success("验证码已发送！");
          this.startEmailCountdown(); // 启动倒计时
        } else {
          this.$message.error(`发送验证码失败: ${result.message}`);
        }
      } catch (error) {
        console.error("发送验证码失败:", error);
        this.$message.error("发送验证码失败，请稍后重试！");
      }
    },

    // 从后端获取用户信息
    async fetchUserInfo() {
      try {
        const token = localStorage.getItem("token"); // 获取本地存储的 token
        const userId = localStorage.getItem("id"); // 获取用户 ID
        const url = `/api/User/getUserById?id=${userId}`; // 拼接后端接口地址

        const response = await fetch(url, {
          headers: { Authorization: `Bearer ${token}` }, // 携带 token 验证身份
        });

        const data = await response.json();
        if (data.code === "200") {
          this.phone = data.data.tel; // 将后端返回的手机号赋值到 phone
          this.email = data.data.mail; // 将后端返回的邮箱赋值到 email
        } else {
          throw new Error(data.message || "获取用户信息失败");
        }
      } catch (error) {
        console.error("获取用户信息失败:", error);
        this.$message.error("获取用户信息失败，请稍后重试！");
      }
    },
    // 邮箱验证码倒计时
    startEmailCountdown() {
      this.emailCountdown = 60; // 初始化倒计时
      const timer = setInterval(() => {
        if (this.emailCountdown > 0) {
          this.emailCountdown--;
        } else {
          clearInterval(timer); // 倒计时结束后清除定时器
        }
      }, 1000);
    },
    // 确认绑定邮箱
    async confirmEmail() {
      try {
        const params = {
          username: 'xju1001', // 假设这是用户名，可以根据需求修改
          email: this.emailForm.email, // 获取用户输入的邮箱
          code: this.emailForm.code,   // 获取用户输入的验证码
        };

        const response = await fetch("/api/api/email/bind", {
          method: "POST", // 使用 POST 请求
          body: `username=${encodeURIComponent(params.username)}&email=${encodeURIComponent(params.email)}&code=${encodeURIComponent(params.code)}`, // URL 编码
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded', // 设置请求体的类型
          }
        });

        const result = await response.json();
        if (result.code === "200") {
          this.$message.success("绑定成功！"); // 显示绑定成功消息
          this.showEmailDialog = false; // 关闭邮箱绑定弹窗
        } else {
          this.$message.error(`添加失败: ${result.message}`); // 显示错误信息
        }
      } catch (error) {
        console.error("绑定邮箱失败:", error);
        this.$message.error("添加失败，请稍后重试！"); // 捕获错误并给出反馈
      }
    },
    // 确认更换邮箱
    async confirmChangeEmail() {
      try {
        const params = {
          username: "xju1001", // 替换为实际用户名
          email: this.changeEmailForm.email,
          code: this.changeEmailForm.code,
        };

        const response = await fetch("/api/api/email/bind", {
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
          body: `username=${encodeURIComponent(params.username)}&email=${encodeURIComponent(params.email)}&code=${encodeURIComponent(params.code)}`,
        });

        const result = await response.json();
        if (result.code === "200") {
          this.$message.success("邮箱更换成功！");
          this.email = this.changeEmailForm.email; // 更新显示的邮箱
          this.showChangeEmailDialog = false; // 关闭弹窗
        } else {
          this.$message.error(`更换失败: ${result.message}`);
        }
      } catch (error) {
        console.error("更换邮箱失败:", error);
        this.$message.error("更换邮箱失败，请稍后重试！");
      }
    },
  },
};
</script>

<style scoped>
.security-settings {
  padding: 20px;
}

.box-card {
  padding: 20px;
  margin: 0 auto;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.setting-item {
  margin-bottom: 20px;
}

.masked-password {
  font-size: 14px;
}

.action-buttons {
  text-align: right;
}

h2 {
  font-size: 28px; /* 增大标题字体 */
  font-weight: bold; /* 标题加粗 */
  color: #333; /* 标题颜色 */
  margin-bottom: 30px; /* 增加标题和内容之间的间距 */
}

</style>
